/*
http://web.archive.org/web/20100212231527/http://ouwehand.net/~peter/lcd/lcd.shtml
*/

#include <stdbool.h>
#include <unistd.h>

#include "system.h"
#include "altera_avalon_pio_regs.h"
#include "altera_avalon_lcd_16207_regs.h"
#include "alt_types.h"

#include "globals.h"
#include "lcd.h"

static bool lcd_initialised = false;

void InitialiseLCD(void)
{
    IOWR_ALTERA_AVALON_LCD_16207_COMMAND(LCD_BASE, 0x38);
    usleep(100000);
    IOWR_ALTERA_AVALON_LCD_16207_COMMAND(LCD_BASE, 0x08);
    usleep(50000);
    IOWR_ALTERA_AVALON_LCD_16207_COMMAND(LCD_BASE, 0x01);
    usleep(50000);
    IOWR_ALTERA_AVALON_LCD_16207_COMMAND(LCD_BASE, 0x0F);
    usleep(50000);
    
    /* End of initialisation */
    lcd_initialised = true;
    return;
}

void ClearLCD(void)
{
    IOWR_ALTERA_AVALON_LCD_16207_COMMAND(LCD_BASE, 0x01);
    usleep(10000);
}

void WriteLCD(const char * str)
{
    char * s_ptr = (char *) str;
    
    ClearLCD();
    if ((str != NULL) && (*str != '\0'))
    {
        while (*s_ptr != '\0')
        {
            if (*s_ptr == '\n')
            {
                IOWR_ALTERA_AVALON_LCD_16207_COMMAND(LCD_BASE, 0xC0);
            }
            else
            {
                IOWR_ALTERA_AVALON_LCD_16207_DATA(LCD_BASE, *s_ptr);
            }
            
            usleep(1000);
            s_ptr++;
        }
    }
    
    return;
}

